/**
 * Created by Administrator on 2017-9-8.
 */
~function () {
	if(typeof window.JKJY == 'undefined') {
		window.JKJY = {};
	}

	window.JKJY = _merge(JKJY, {
		merge: _merge,
		mg: _merge,

		ip2city:_ip2city,
		currentip2city:_currentip2city
	});

	function _merge() {
		var target = arguments[0];

		if(!target) {
			target = {};
		}

		for(var i=arguments.length-1; i>=1; i--) {
			for(var k in arguments[i]) {
				if(arguments[i].hasOwnProperty(k)) {
					target[k] = arguments[i][k];
				}
			}
		}

		return target;
	}

	/**
	 * 获取当前城市
	 * @param callback 回调函数, 函数参数第一个为当前城市或国家名称, 第二个是详细信息
	 * @param beginCallback 开始查询时的回调函数
	 */
	function _currentip2city(callback, beginCallback) {
		_ip2city('-', callback, beginCallback);
	}

	/**
	 * 获取指定ip的城市
	 * @param ip IP地址
	 * @param callback 回调函数, 函数参数第一个为当前城市或国家名称, 第二个是详细信息
	 * @param beginCallback 开始查询时的回调函数
	 */
	function _ip2city(ip, callback, beginCallback) {
		if(typeof window.IPCityCaches == 'undefined') {
			window.IPCityCaches = {};
		}

		var cityInfo = null;

		if(!ip) {
			ip = '-';
		}

		if(window.IPCityCaches[ip]) {
			cityInfo = window.IPCityCaches[ip];
		}

		if(cityInfo) {
			callback(cityInfo['text'], cityInfo);
		} else {
			var script = document.createElement('script');

			script.onload = function () {
				if(remote_ip_info) {
					remote_ip_info['text'] = remote_ip_info['city'] ? remote_ip_info['city'] : remote_ip_info['province'];
					remote_ip_info['text'] = remote_ip_info['text'] ? remote_ip_info['text'] : remote_ip_info['country'];
					remote_ip_info.ok = true;
					IPCityCaches[ip] = remote_ip_info;
					callback(remote_ip_info['text'], remote_ip_info);
					remote_ip_info=null ;
				} else {
					callback(null, {});
				}
			};

			script.type = "text/javascript";
			if(ip == '-') {
				script.src = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js";
			} else {
				script.src = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=" + ip;
			}

			beginCallback && beginCallback();
			document.body.appendChild(script);
		}
	}
}();